//
//  AY_PageReadViewController.m
//  AiYue
//
//  Created by mac on 2023/10/18.
//

#import "AY_PageReadViewController.h"
#import "AY_ReadViewController.h"
#import "AYReadParser.h"
#import "AY_ReadMenu.h"
#import "AY_AudioViewController.h"
#import "BDSSpeechSynthesizer.h"
#import "AY_BookDetailViewController.h"
#import "AY_LastPageViewController.h"

@implementation UIPageViewController (EnlargeTapRegion)
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
        return NO;
    }
    return YES;
}
@end

@interface SXReadPageView : UIView
@property (nonatomic,strong) UIView *brightnessView;
@property (nonatomic,strong) UIView *huYanView;
@end

@implementation SXReadPageView
-(void)addSubview:(UIView *)view
{
    if (view != self.brightnessView && self.brightnessView && view != self.huYanView && self.huYanView) {
        NSInteger index = [self.subviews indexOfObject:self.brightnessView];
        NSInteger index1 = [self.subviews indexOfObject:self.huYanView];
        if (index != NSNotFound) {
            [self insertSubview:view atIndex:index];
        }else if (index1 != NSNotFound){
            [self insertSubview:view atIndex:index];
        }else{
            [super addSubview:view];
        }
    }else{
        [super addSubview:view];
    }
}
@end

@interface AY_PageReadViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource,SXAReadViewControllerDelegate,SXMenuViewDelegate, SXLoadingDelegate, SXAudioDelegate>

@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,strong) AY_ReadMenu *menuView;
@property (nonatomic,strong) NSMutableArray *chapters;
@property (nonatomic,strong) BookContentModel *bookContentModel;
@property (nonatomic,strong) BookContentModel *nextBookContentModel;
@property (nonatomic,strong) BookContentModel *upBookContentModel;
@property (nonatomic,strong) UIView *brightnessView;
@property (nonatomic,strong) UIView *huYanView;
@property (strong,nonatomic) AY_LoadingView *loadingView;
@property (strong,nonatomic) AY_AudioViewController *audioView;
@property (strong, nonatomic) NSString *bookId;
@property (strong, nonatomic) NSString *sendPage;
@property (strong, nonatomic) NSString *sendChapterIndex;
@property (strong, nonatomic) BookModel *bookModel;
@property (nonatomic,assign) NSInteger startTimer; // 开始时间
@property (nonatomic, strong) UserInfo * userInfoModel;
@end

@implementation AY_PageReadViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self barStyleBlack];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self barStyleBlack];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
}

-(void)loadView
{
    UIView *view = [[SXReadPageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = view;
}

- (void)backAction {
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [AYApiRequest getUpInsertReadTime:[NSString stringWithFormat:@"%ld",[[AYTool getCurrentTime] integerValue] - self.startTimer] articleId:self.bookId Success:^(AY_QiuBookModel * _Nonnull pkg) {
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getBookDetailWithBookId:self.bookId Success:^(AY_BookDetailModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.bookModel = pkg.data;
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (self.bookModel.shelfFlag.intValue == 0) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"提示"                                            message: @"确认将此书加入书架？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [self addBookApiWithInfo:YES];
            }];
            // KVC修改字体颜色
            [sureAction setValue:COLOR(@"FF5443") forKey:@"_titleTextColor"];
            [alertController addAction:sureAction];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self saveBook];
            }];
            [cancelAction setValue:COLOR(@"999999") forKey:@"_titleTextColor"];
            [alertController addAction:cancelAction];
            
            [self presentViewController: alertController animated: YES completion: nil];
        }else {
            [self addBookApiWithInfo:NO];
        }
    });
}

// 本地未在书架的数据
- (void)saveBook {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [AYTool saveBooksWithBookId:self.bookId andPage:currentController.page andChapterIndex:currentController.charpterIndex];
    [self quitRead];
}

- (void)quitRead {
    [self.audioView.view removeFromSuperview];
    [AY_ReadBookTool stopSpeak];
//    [[BDSSpeechSynthesizer sharedInstance] cancel];
//    [BDSSpeechSynthesizer releaseInstance];
    [self.navigationController popViewControllerAnimated:YES];
}

// loading返回
- (void)popAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBookApiWithInfo:(BOOL)isInfo {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [AYApiRequest addBookWithBookId:self.bookId andChapterNo:[NSString stringWithFormat:@"%ld",currentController.charpterIndex + 1] andPageNo:[NSString stringWithFormat:@"%ld",currentController.page + 1] Success:^(AY_BaseModel * _Nonnull pkg) {
        if (isInfo) {
            ShowToast(@"添加书架成功");
        }
        [self quitRead];
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

#pragma mark - 加入书架
- (void)addBookSelfAction:(UIButton *)btn {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [AYApiRequest addBookWithBookId:self.bookId andChapterNo:[NSString stringWithFormat:@"%ld",currentController.charpterIndex + 1] andPageNo:[NSString stringWithFormat:@"%ld",currentController.page + 1] Success:^(AY_BaseModel * _Nonnull pkg) {
        ShowToast(@"添加书架成功");
        btn.hidden = YES;
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateUserInfo];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

- (void)sendBookId:(NSString *)bookId andPage:(NSString *)page andChapterIndex:(NSString *)chapterIndex {
    _bookId = bookId;
    _sendPage = page.integerValue < 0 ? 0 : page;
    _sendChapterIndex = chapterIndex.integerValue < 0 ? 0 : chapterIndex;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navBarAlpha = 0;
    self.gk_navLeftBarButtonItem = nil;
        
    self.pageViewController.view.frame = self.view.bounds;
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    [self loadChapterData];
    
    SXReadPageView *view = (SXReadPageView *)self.view;
    view.brightnessView = self.brightnessView;
    [self.view addSubview:self.brightnessView];
    view.huYanView = self.huYanView;
    [self.view addSubview:self.huYanView];
    [self.huYanView addSubview:self.gk_navigationBar];
    [[AYTool lastWindow] addSubview:self.audioView.view];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ZFREFRESH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:BOOKDOUGM object:nil];
    
    /* 禁用右滑返回 */
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
    
    self.startTimer = [[AYTool getCurrentTime] integerValue];
}

- (void)loadChapterData {
    [self.loadingView loadingInView:self.view];

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [AYApiRequest getBookChapterListWithPageNum:@"1" andPageSize:@"10000" andArticleId:self.bookId Success:^(AY_ChapterModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.chapters = [NSMutableArray arrayWithArray:pkg.rows];
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
        [self.loadingView refresh];
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getBookDetailWithBookId:self.bookId Success:^(AY_BookDetailModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.bookModel = pkg.data;
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
        [self.loadingView refresh];
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (self.chapters.count > 0) {
            ReadChapterModel *model = self.chapters[self.sendChapterIndex.integerValue];
            [self loadBookContentWithChapterId:model.chapterId andAnimated:YES andChapterIndex:self.sendChapterIndex.intValue andPage:self.sendPage];
        }
    });
}

- (void)updateUserInfo {
    [AYApiRequest getUserInfoSuccess:^(AY_UserModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.userInfoModel = pkg.data;
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)refresh {
    [AYMMKV setBool:YES forKey:AUTO];
    [self updateUserInfo];
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    ReadChapterModel *model = self.chapters[currentController.charpterIndex];
    [self loadBookContentWithChapterId:model.chapterId andAnimated:NO andChapterIndex:currentController.charpterIndex andPage:[NSString stringWithFormat:@"%ld",currentController.page]];
}

- (void)refreshAction {
    [self loadChapterData];
}

- (void)didSelectCharpterWithIndex:(ReadChapterModel *)readChapterModel andChapterIndex:(NSInteger)index {
    [self invokeMenu:self.pageViewController.viewControllers.firstObject];
    [self loadBookContentWithChapterId:readChapterModel.chapterId andAnimated:NO andChapterIndex:index andPage:@"0"];
}

- (void)loadBookContentWithChapterId:(NSString *)chapterId andAnimated:(BOOL)animated andChapterIndex:(NSInteger)index andPage:(NSString *)page {
    [AYApiRequest getBookContentWithChapterId:chapterId andAuto:[AYMMKV getBoolForKey:AUTO defaultValue:YES] ? @"1" : @"0" Success:^(AY_BookContentModel * _Nonnull pkg) {
        self.bookContentModel = pkg.data;
        [self loadContent:animated andChapterIndex:index andPage:page];
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)loadContent:(BOOL)animated andChapterIndex:(NSInteger)index andPage:(NSString *)page {
    dispatch_main_async_safe(^{
        [AYReadParser paginateWithContent: kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
            [self.loadingView dismiss];
            [self.pageViewController setViewControllers:@[[self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:page.intValue pages:pages] page:page.intValue totalPage:pages.count charpterIndex:index totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO]] direction:UIPageViewControllerNavigationDirectionReverse animated:animated completion:nil];
            [self p_saveRecord];
        }];
    });
}

-(AY_ReadViewController *)p_creatReadController:(NSString *)charpter content:(NSAttributedString *)content page:(NSInteger)page totalPage:(NSInteger)totalPage charpterIndex:(NSInteger)index totalCharpter:(NSInteger)total charpterModel:(BookContentModel *)bookContentModel charpterContent:(NSAttributedString *)charpterContent pages:(NSArray *)pages mirror:(BOOL)mirror {
    AY_ReadViewController * readController = [[AY_ReadViewController alloc] init];
    readController.delegate = self;
    readController.articleid = _bookId;
    readController.bookContentModel = bookContentModel;
    readController.charpterContent = charpterContent;
    readController.mirror = mirror;
    readController.pages = pages;
    [readController showPyView:kStringIsEmpty(self.bookContentModel.contentUrl)];
    [readController setCharpter:charpter content:content page:page totalPage:totalPage charpterIndex:index totalCharpter:total];
    return readController;
}
    
-(void)invokeMenu:(AY_ReadViewController *)controller {
    if (self.menuView.superview) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        [self setNeedsStatusBarAppearanceUpdate];
        [self.menuView dismiss];
    }else {
        //隐藏=YES,显示=NO; Animation:动画效果
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        [self setNeedsStatusBarAppearanceUpdate];
        AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
        self.menuView = [[AY_ReadMenu alloc] init];
        self.menuView.charpters = self.chapters;
        self.menuView.currentChapter = currentController.charpterIndex;
        self.menuView.bookModel = self.bookModel;
        self.menuView.delegate = self;
        self.menuView.userInfoModel = self.userInfoModel;
        [self.menuView showInView:self.view];
    }
}

- (void)p_saveRecord {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    self.audioView.isInit = NO;
    [self.audioView setContent:currentController.charpterContent andChapters:self.chapters andPage:currentController.page andChapterIndex:currentController.charpterIndex andPages:currentController.pages andIsFanye:YES andChapterTitle:currentController.charpter];
    if (self.bookModel.shelfFlag.intValue == 1) {
        [AYApiRequest addBookWithBookId:self.bookId andChapterNo:[NSString stringWithFormat:@"%ld",currentController.charpterIndex + 1] andPageNo:[NSString stringWithFormat:@"%ld",currentController.page + 1] Success:^(AY_BaseModel * _Nonnull pkg) {
        } failure:^(int status, NSString * _Nonnull info) {
            ShowToast(@"亲，网络不顺畅哟~");
        }];
    }
}

#pragma mark - 护眼
- (void)huyanChange {
    self.huYanView.alpha = [AYMMKV getFloatForKey:HuYanAlpha defaultValue:0];
}

#pragma mark - 亮度
- (void)brightnessChange {
    self.brightnessView.alpha = [AYMMKV getFloatForKey:Brightness defaultValue:0];
}

#pragma mark - 字号/间距
- (void)fontChange {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [AYReadParser paginateWithContent: kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
        [self.loadingView dismiss];
        [self.pageViewController setViewControllers:@[[self p_creatReadController:currentController.charpter content:[self p_subGetCurPageContentWithContent:content page:currentController.page pages:pages] page:currentController.page totalPage:pages.count charpterIndex:currentController.charpterIndex totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO]] direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
        [self p_saveRecord];
    }];
}

#pragma mark - 听书
- (void)showAudioView {
    self.audioView.isQuit = NO;
    self.audioView.isInit = YES;
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    self.audioView.bookModel = self.bookModel;
    [self.audioView setContent:currentController.charpterContent andChapters:self.chapters andPage:currentController.page andChapterIndex:currentController.charpterIndex andPages:currentController.pages andIsFanye:NO andChapterTitle:currentController.charpter];
    [UIView animateWithDuration:0.3f animations:^{
        self.audioView.view.frame = self.view.bounds;
    }];
}

#pragma mark - 听书跳转详情
- (void)pushBookDetailWithBookId:(NSString *)bookId {
//    [[BDSSpeechSynthesizer sharedInstance] cancel];
//    [BDSSpeechSynthesizer releaseInstance];
    [AY_ReadBookTool stopSpeak];
    self.audioView.isInit = NO;
    [UIView animateWithDuration:0.3f animations:^{
        self.audioView.view.frame = CGRectMake(0, SCREEN_H, SCREEN_W, SCREEN_H);
    }];
    AY_BookDetailViewController *bookDetailVC = [[AY_BookDetailViewController alloc] init];
    bookDetailVC.bookId = bookId;
    [self.navigationController pushViewController:bookDetailVC animated:YES];
}

- (void)audioDismiss {
    [UIView animateWithDuration:0.3f animations:^{
        self.audioView.view.frame = CGRectMake(0, SCREEN_H, SCREEN_W, SCREEN_H);
    }];
}

-(void)cancelShowMenu:(AY_ReadMenu *)menu
{
    [self invokeMenu:self.pageViewController.viewControllers.firstObject];
}

- (void)colorChange {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [currentController setColors];
}

#pragma mark - 听书下一页/上一页
- (void)audioChangePage:(NSInteger)page {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [_pageViewController.view removeFromSuperview];
    [_pageViewController removeFromParentViewController];
    _pageViewController = nil;
    [self addChildViewController:self.pageViewController];
    [self.pageViewController setViewControllers:@[[self p_creatReadController:currentController.charpter content:[self p_subGetCurPageContentWithContent:currentController.charpterContent page:page pages:currentController.pages] page:page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:currentController.charpterContent pages:currentController.pages mirror:NO]] direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
    [self p_saveRecord];
}

#pragma mark - 点击目录听书
- (void)audioDidselectChapter:(NSInteger)index {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    if (currentController.charpterIndex == self.chapters.count - 1) {
//        ShowToast(@"当前已是最后一章");
        AY_LastPageViewController *lastVC = [[AY_LastPageViewController alloc] init];
        lastVC.bookModel = self.bookModel;
        [self.navigationController pushViewController:lastVC animated:YES];
        return;
    }
    [_pageViewController.view removeFromSuperview];
    [_pageViewController removeFromParentViewController];
    _pageViewController = nil;
    [self addChildViewController:self.pageViewController];
    
    __block AY_ReadViewController * readController;
    NSInteger charpter = currentController.charpterIndex; //当前章节
    ReadChapterModel *chapterModel = self.chapters[index];
    NSString *charpterId = chapterModel.chapterId;
    [AYApiRequest getBookContentWithChapterId:charpterId andAuto:[AYMMKV getBoolForKey:AUTO defaultValue:YES] ? @"1" : @"0" Success:^(AY_BookContentModel * _Nonnull pkg) {
        self.bookContentModel = pkg.data;
        [AYReadParser paginateWithContent:kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
            readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:0 pages:pages] page:0 totalPage:pages.count charpterIndex:index totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
            [self.pageViewController setViewControllers:@[readController] direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
        }];
        [self p_saveRecord];
        
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

#pragma mark - 听书上一章/下一章
- (void)audioChangeChapter:(BOOL)isNext {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    if (currentController.charpterIndex == 0) {
        if (!isNext) {
            ShowToast(@"当前已是第一章");
            return;
        }
    }
    if (currentController.charpterIndex == self.chapters.count - 1) {
//        ShowToast(@"当前已是最后一章");
        AY_LastPageViewController *lastVC = [[AY_LastPageViewController alloc] init];
        lastVC.bookModel = self.bookModel;
        [self.navigationController pushViewController:lastVC animated:YES];
        return;
    }
    [_pageViewController.view removeFromSuperview];
    [_pageViewController removeFromParentViewController];
    _pageViewController = nil;
    [self addChildViewController:self.pageViewController];
    
    __block AY_ReadViewController * readController;
    NSInteger charpter = currentController.charpterIndex; //当前章节
    ReadChapterModel *chapterModel = isNext ? self.chapters[charpter+1] : self.chapters[charpter-1];
    NSString *charpterId = chapterModel.chapterId;
    [AYApiRequest getBookContentWithChapterId:charpterId andAuto:[AYMMKV getBoolForKey:AUTO defaultValue:YES] ? @"1" : @"0" Success:^(AY_BookContentModel * _Nonnull pkg) {
        self.bookContentModel = pkg.data;
        [AYReadParser paginateWithContent:kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
            readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:!isNext?pages.count-1:0 pages:pages] page:!isNext?pages.count-1:0 totalPage:pages.count charpterIndex:!isNext ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
            [self.pageViewController setViewControllers:@[readController] direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
        }];
        [self p_saveRecord];
        
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

#pragma mark - 更改翻页
- (void)changePageType:(UIButton *)btn {
    [self invokeMenu:self.pageViewController.viewControllers.firstObject];
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    [_pageViewController.view removeFromSuperview];
    [_pageViewController removeFromParentViewController];
    _pageViewController = nil;
    [self addChildViewController:self.pageViewController];
    [self.pageViewController setViewControllers:@[currentController] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}

#pragma mark - UIPageViewControllerDataSource
#pragma mark - UIPageViewContrillerDelegate
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed) {
        [self p_saveRecord];
        
    }
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    if (self.pageViewController.transitionStyle == UIPageViewControllerTransitionStylePageCurl) {
        AY_ReadViewController *currentController = (AY_ReadViewController *)viewController;
        if (!currentController.mirror) {
            AY_ReadViewController *mirrorController = (AY_ReadViewController *)[self p_afterOrBeforeWithViewController:viewController before:YES mirror:YES];
            return mirrorController;
        }
        return [self p_creatReadController:currentController.charpter content:currentController.content page:currentController.page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:currentController.charpterContent pages:currentController.pages mirror:NO];
    }
    return [self p_afterOrBeforeWithViewController:viewController before:YES];
}

- (void)lastPage:(AY_ReadViewController *)controller {
    if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 1 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 3){
        [self p_setAfterOrBeforeViewControllerWithBefore:YES mirror:YES];
    }
    else{
        [self p_setAfterOrBeforeViewControllerWithBefore:YES mirror:NO];
    }
    [self p_saveRecord];
}

- (void)nextPage:(AY_ReadViewController *)controller {
    if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 1 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 3){
        [self p_setAfterOrBeforeViewControllerWithBefore:NO mirror:YES];
    }
    else{
        [self p_setAfterOrBeforeViewControllerWithBefore:NO mirror:NO];
    }
    [self p_saveRecord];
}

-(void)p_setAfterOrBeforeViewControllerWithBefore:(BOOL)before mirror:(BOOL)mirror {
    AY_ReadViewController *currentController = (AY_ReadViewController *)_pageViewController.viewControllers.firstObject;
    NSInteger page = currentController.page;   //当前页数
    NSInteger charpter = currentController.charpterIndex; //当前章节
    NSAttributedString *charpterContent = currentController.charpterContent;    //当前章节内容
    NSArray *pages = currentController.pages;       //分页信息数组
    
    UIPageViewControllerNavigationDirection direction;
    if (before) {
        direction = UIPageViewControllerNavigationDirectionReverse;
    }
    else{
        direction = UIPageViewControllerNavigationDirectionForward;
    }
    
    BOOL animate;
    if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 0) {
        animate = NO;
    }
    else{
        animate = YES;
    }
    if (before) {
        if (page == 0 && charpter == 0) {
            //第一章，第一页，不用做任何处理
            return;
        }
    }else{
        if (page >= pages.count-1 && charpter == self.chapters.count-1) {
            //最后一张最后一页，不用做任何处理
            AY_LastPageViewController *lastVC = [[AY_LastPageViewController alloc] init];
            lastVC.bookModel = self.bookModel;
            [self.navigationController pushViewController:lastVC animated:YES];
            return;
        }
    }
    if (before) {
        if (page == 0 && charpter == 0) {
            //第一章，第一页，不用做任何处理
            return;
        }
    }else{
        if (page >= pages.count-1 && charpter == self.chapters.count-1) {
            //最后一张最后一页，不用做任何处理
            AY_LastPageViewController *lastVC = [[AY_LastPageViewController alloc] init];
            lastVC.bookModel = self.bookModel;
            [self.navigationController pushViewController:lastVC animated:YES];
            return;
        }
    }
    // 如果是
    if ((before && (page == 0)) || (!before && (page >= pages.count-1) )) {
        //上一章的数据 或者下一章的数据
        __block AY_ReadViewController * readController;
        ReadChapterModel *chapterModel = before ? self.chapters[charpter-1] : self.chapters[charpter+1];
        NSString *charpterId = chapterModel.chapterId;
        [AYApiRequest getBookContentWithChapterId:charpterId andAuto:[AYMMKV getBoolForKey:AUTO defaultValue:YES] ? @"1" : @"0" Success:^(AY_BookContentModel * _Nonnull pkg) {
            self.bookContentModel = pkg.data;
            
            [AYReadParser paginateWithContent:kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
                if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 1 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 3) {
                    if (before) {
                        //上一章
                        AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:pages.count - 1 pages:pages] page:pages.count-1 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                        AY_ReadViewController * mirror_readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:pages.count - 1 pages:pages] page:pages.count-1 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:YES];
                        [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
                    }else {
                        //下一章
                        AY_ReadViewController * mirror_readController = [self p_creatReadController:currentController.charpter content:currentController.content page:currentController.page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:content pages:pages mirror:YES];
                        //后一页
                        AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:0 pages:pages] page:0 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                        [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
                    }
                }else {
                    AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:before?pages.count-1:0 pages:pages] page:before?pages.count-1:0 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                    [self.pageViewController setViewControllers:@[readController] direction:direction animated:animate completion:nil];
                }
                // 保存进度
                [self p_saveRecord];
            }];
            
        } failure:^(int status, NSString * _Nonnull info) {
            ShowToast(@"亲，网络不顺畅哟~");
        }];
    }else {
        if (mirror) {
            if (before) {
                AY_ReadViewController *readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:charpterContent page:page - 1 pages:pages] page:page - 1 totalPage:pages.count charpterIndex:charpter totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:charpterContent pages:pages mirror:NO];
                AY_ReadViewController *mirror_readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:charpterContent page:page - 1 pages:pages] page:page - 1 totalPage:pages.count charpterIndex:charpter totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:charpterContent pages:pages mirror:YES];
                [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
            }else {
                AY_ReadViewController *mirror_readController = [self p_creatReadController:currentController.charpter content:currentController.content page:currentController.page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:currentController.charpterContent pages:currentController.pages mirror:YES];
                AY_ReadViewController *readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:charpterContent page:page+1 pages:pages] page:page+1 totalPage:pages.count charpterIndex:charpter totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:charpterContent pages:pages mirror:NO];
                [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
            }
        }else {
            AY_ReadViewController *readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:charpterContent page:before?page-1:page+1 pages:pages] page:before?page-1:page+1 totalPage:pages.count charpterIndex:charpter totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:charpterContent pages:pages mirror:NO];
            [self.pageViewController setViewControllers:@[readController] direction:direction animated:animate completion:nil];
        }
    }
    
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    if (self.pageViewController.transitionStyle == UIPageViewControllerTransitionStylePageCurl) {
        AY_ReadViewController *currentController = (AY_ReadViewController *)viewController;
        if (!currentController.mirror) {
            return [self p_creatReadController:self.bookContentModel.title content:currentController.content page:currentController.page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:currentController.charpterContent pages:currentController.pages mirror:YES];
        }
    }
    return [self p_afterOrBeforeWithViewController:viewController before:NO];
}

/// 返回前一个或者后一个控制器
/// @param controller 当前控制区内
/// @param before 是否是前一个控制器
-(UIViewController *)p_afterOrBeforeWithViewController:(UIViewController *)controller before:(BOOL)before
{
    return [self p_afterOrBeforeWithViewController:controller before:before mirror:NO];
}

-(UIViewController *)p_afterOrBeforeWithViewController:(UIViewController *)controller before:(BOOL)before mirror:(BOOL)mirror {
    AY_ReadViewController *currentController = (AY_ReadViewController *)controller;
    NSInteger page = currentController.page;   //当前页数
    NSInteger charpter = currentController.charpterIndex; //当前章节
    NSAttributedString *charpterContent = currentController.charpterContent;    //当前章节内容
    BookContentModel *bookContentModel = currentController.bookContentModel;   //当前章节信息
    NSArray *pages = currentController.pages;       //分页信息数组
    UIPageViewControllerNavigationDirection direction;
    if (before) {
        direction = UIPageViewControllerNavigationDirectionReverse;
    }
    else{
        direction = UIPageViewControllerNavigationDirectionForward;
    }
    BOOL animate;
    if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 0) {
        animate = NO;
    }
    else{
        animate = YES;
    }
    if (before) {
        if (page == 0 && charpter == 0) {
            //第一章，第一页，不用做任何处理
            return nil;
        }
    }
    else{
        if (page >= pages.count-1 && charpter == self.chapters.count-1) {
            //最后一张最后一页，不用做任何处理
            AY_LastPageViewController *lastVC = [[AY_LastPageViewController alloc] init];
            lastVC.bookModel = self.bookModel;
            [self.navigationController pushViewController:lastVC animated:YES];
            return nil;
        }
    }
    
    if ((before && (page == 0)) || (!before && (page >= pages.count-1) )) {
        //上一章的数据 或者下一章的数据
        __block AY_ReadViewController * readController;
        ReadChapterModel *chapterModel = before ? self.chapters[charpter-1] : self.chapters[charpter+1];
        NSString *charpterId = chapterModel.chapterId;
        [AYApiRequest getBookContentWithChapterId:charpterId andAuto:[AYMMKV getBoolForKey:AUTO defaultValue:YES] ? @"1" : @"0" Success:^(AY_BookContentModel * _Nonnull pkg) {
            self.bookContentModel = pkg.data;
            [AYReadParser paginateWithContent:kStringIsEmpty(self.bookContentModel.contentUrl) ? self.bookContentModel.chapterContent : [AYTool getContentWithUrl:self.bookContentModel.contentUrl] charpter:self.bookContentModel.title bounds:CGRectMake(0, 0, SCREEN_W-kLeftMargin-kRightMargin, SCREEN_H-kTopMargin-kBottomMargin) complete:^(NSAttributedString * _Nonnull content, NSArray * _Nonnull pages) {
                if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 1 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 3) {
                    if (before) {
                        //上一章
                        AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:pages.count - 1 pages:pages] page:pages.count-1 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                        AY_ReadViewController * mirror_readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:pages.count - 1 pages:pages] page:pages.count-1 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:YES];
                        [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
                    }else {
                        //下一章
                        AY_ReadViewController * mirror_readController = [self p_creatReadController:currentController.charpter content:currentController.content page:currentController.page totalPage:currentController.totalPage charpterIndex:currentController.charpterIndex totalCharpter:currentController.totalCharpter charpterModel:currentController.bookContentModel charpterContent:content pages:pages mirror:YES];
                        //后一页
                        AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:0 pages:pages] page:0 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                        [self.pageViewController setViewControllers:@[readController,mirror_readController] direction:direction animated:animate completion:nil];
                    }
                }else {
                    AY_ReadViewController * readController = [self p_creatReadController:self.bookContentModel.title content:[self p_subGetCurPageContentWithContent:content page:before?pages.count-1:0 pages:pages] page:before?pages.count-1:0 totalPage:pages.count charpterIndex:before ? charpter - 1 : charpter + 1 totalCharpter:self.chapters.count charpterModel:self.bookContentModel charpterContent:content pages:pages mirror:NO];
                    [self.pageViewController setViewControllers:@[readController] direction:direction animated:animate completion:nil];
                }
                // 保存进度
                [self p_saveRecord];
            }];
        } failure:^(int status, NSString * _Nonnull info) {
            ShowToast(@"亲，网络不顺畅哟~");
        }];
        return readController;
    } else {
        AY_ReadViewController *readController = [self p_creatReadController:bookContentModel.title content:[self p_subGetCurPageContentWithContent:charpterContent page:before?page-1:page+1 pages:pages] page:before?page-1:page+1 totalPage:pages.count charpterIndex:charpter totalCharpter:self.chapters.count charpterModel:bookContentModel charpterContent:charpterContent pages:pages mirror:mirror];
        return readController;
    }
}

-(UIPageViewController *)pageViewController
{
    if (!_pageViewController) {
        UIPageViewControllerTransitionStyle style;
        UIPageViewControllerNavigationOrientation navigationOrientation;
        int pageType = [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1];
        switch (pageType) {
            case 0:
            case 1:
                style = UIPageViewControllerTransitionStylePageCurl;
                navigationOrientation = UIPageViewControllerNavigationOrientationHorizontal;
                break;
            case 2:
                style = UIPageViewControllerTransitionStyleScroll;
                navigationOrientation = UIPageViewControllerNavigationOrientationHorizontal;
                break;
            case 3:
                style = UIPageViewControllerTransitionStylePageCurl;
                navigationOrientation = UIPageViewControllerNavigationOrientationVertical;
                break;
            case 4:
                style = UIPageViewControllerTransitionStyleScroll;
                navigationOrientation = UIPageViewControllerNavigationOrientationVertical;
                break;
            default:
                style = UIPageViewControllerTransitionStylePageCurl;
                navigationOrientation = UIPageViewControllerNavigationOrientationVertical;
                break;
        }
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:style navigationOrientation:navigationOrientation options:nil];
        _pageViewController.delegate = self;
        _pageViewController.view.backgroundColor = [UIColor clearColor];
        if (pageType != 0 && pageType != 2 && pageType != 4) {
//            _pageViewController.dataSource = self;
            _pageViewController.doubleSided = (style == UIPageViewControllerTransitionStylePageCurl);
        }
        [self.view addSubview:_pageViewController.view];
    }
    return _pageViewController;
}

-(NSAttributedString *)p_subGetCurPageContentWithContent:(NSAttributedString *)conetnt page:(NSInteger)page pages:(NSArray *)pages
{
    NSInteger index = page;
    if (index < 0) {
        index = 0;
    }
    if (index >= pages.count) {
        index = pages.count - 1;
    }
    NSInteger loc = [pages[index] integerValue];
    NSInteger len = 0;
    if (index<pages.count-1) {
        len = [pages[index+1] integerValue] - loc;
    }
    else{
        len = conetnt.length - loc;
    }
    return [conetnt attributedSubstringFromRange:NSMakeRange(loc, len)];
    
}

- (UIView *)huYanView
{
    if (!_huYanView) {
        _huYanView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _huYanView.backgroundColor = COLOR(@"7A5E20");
        _huYanView.alpha = [AYMMKV getFloatForKey:HuYanAlpha defaultValue:0];
        _huYanView.userInteractionEnabled = NO;
    }
    return _huYanView;
}

-(UIView *)brightnessView
{
    if (!_brightnessView) {
        _brightnessView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _brightnessView.backgroundColor = [UIColor blackColor];
        _brightnessView.alpha = [AYMMKV getFloatForKey:Brightness defaultValue:0];
        _brightnessView.userInteractionEnabled = NO;
    }
    return _brightnessView;
}

- (AY_LoadingView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[AY_LoadingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _loadingView.backgroundColor = COLOR(@"#F7F5F6");
        _loadingView.delegate = self;
        _loadingView.hideLeftpop = NO;
    }
    return _loadingView;
}

- (AY_AudioViewController *)audioView {
    if (!_audioView) {
        _audioView = [[AY_AudioViewController alloc] init];
        _audioView.view.frame = CGRectMake(0, SCREEN_H, SCREEN_W, SCREEN_H);
        _audioView.delegate = self;
    }
    return _audioView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
